import React, { useEffect, useState, lazy } from 'react'
import { useLocation } from 'react-router-dom'
import { qiankunWindow } from 'vite-plugin-qiankun/dist/helper'
import store from '@/redux/store'
import { updateHarvestInfoAction } from '@/redux/action/harvestInfo'

const ContainerOne = lazy(() => import('@/container/FrameOne'))
const ContainerTwo = lazy(() => import('@/container/FrameTwo'))
const ContainerThree = lazy(() => import('@/container/FrameThree'))
const NotFound = lazy(() => import('@/pages/NotFound'))

interface watchHandlerItf {
  token: string
  harvestId?: string
  projectId: string
  projectTitle?: string
  type: 'readWindow' | 'shareProject'
}

function App() {
  useEffect(() => {
    if (!qiankunWindow.__POWERED_BY_QIANKUN__) watchEditHarvest()
  }, [])

  // 监听
  const watchEditHarvest = () =>
    (window as any).readingWindow?.watchEditHarvest(watchHandler)

  // 监听传递过来的收获信息处理函数
  const watchHandler = async (data: watchHandlerItf) => {
    const { harvestId, projectId, token, projectTitle, type } = data
    setProjectId(projectId)
    setProjectTitle(projectTitle)
    window.localStorage.setItem('token', token)
    store.dispatch(updateHarvestInfoAction({ harvestId, projectId }))

    if (type === 'readWindow') setOption('readWindow')
    if (type === 'shareProject') setOption('shareProject')
  }

  const [projectId, setProjectId] = useState<string>()
  const [projectTitle, setProjectTitle] = useState<string>()

  const { pathname } = useLocation()
  useEffect(() => {
    if (pathname.split('/')[1] == 'chatting') setOption('chatting')
  }, [pathname])

  //
  //
  // 要展现的框架选项
  const [option, setOption] = useState<string>('notFound')
  // 框架选项
  const options = {
    notFound: <NotFound />,
    readWindow: <ContainerOne />,
    shareProject: (
      <ContainerTwo projectId={projectId} projectTitle={projectTitle} />
    ),
    chatting: <ContainerThree />,
  }

  return <>{option ? options[option] : ''}</>
}

export default App
